<?php

namespace App\Http\Controllers\Front\Member\Shop;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ApiController;
use App\Models\Product;
use App\Models\Order;
use App\Http\Resources\Front\Order as OrderResource;
use App\Http\Resources\Front\OrderCollection;
use App\Models\UserAddress;
use Carbon\Carbon;
use DB;

class OrderController extends ApiController
{

    /**
     * 订单
     * 
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax() || $request->wantsJson()) {
            // 异步请求订单
            $limit = $request->input('size', 10);
            $status = $request->input('status', 'all');
    
            $orderOrm = Order::where('shop_id', $request->user()->shop->id)
                ->orderBy('id', 'DESC')->with(['user' => function($query) {
                    $query->select('id', 'name'); // 用户ID，名称
                }])
                ->with(['shop' => function($query) {
                    $query->select('id', 'name'); // 店铺ID，名称
                }])
                ->with(['orderItems']);
    
            if($status && $status !== 'all') {
                $orderOrm->where('status', Order::getOrderStatus($status));
            }
    
            return new OrderCollection($orderOrm->paginate($limit)); 
        }

        return view('front.member.shop.order');
    }

    /**
     * 获取指定订单
     */
    public function show($id, Request $request)
    {
        if ($request->ajax() || $request->wantsJson()) {
            $order = Order::where('shop_id', $request->user()->shop->id)
                ->with(['orderItems'])
                ->with(['user' => function($query) {
                    $query->select('id', 'name');
                }])  
                ->with(['shop' => function($query) {
                    $query->select('id', 'name');
                }])
                ->find($id);

            return $this->success(new OrderResource($order));
        }

        return view('front.member.shop.orderShow', compact('id'));
    }
}
